from rest_framework import serializers
from .models import MovieOrders
from django.utils.timezone import now, timedelta

from drf_movie_rimi.settings import MOVIE_ORDER


class MovieOrdersSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    order_amount = serializers.HiddenField(default=1)

    # 修改订单的价格,订单价格由订座的数量来决定
    def validate(self, attrs):
        amount = 0
        for i in attrs['order_seats']:

            film_piece = i.movie_piece
            # 片场过期 座位被订购了都不能通过验证
            if film_piece.start_time < now():
                raise serializers.ValidationError('片场:{} 已经开始不能购买'.format(film_piece))

            # 座位如果被锁定了或者购买了不能通过验证
            if str(i.status) == str(MOVIE_ORDER['order_status']['ordered']):
                raise serializers.ValidationError('座位:{} 已经被购买了'.format(i))
            # 如果被锁定 查看是否超过锁定期 锁定座位 15分钟内必须支付

            if str(i.status) == str(MOVIE_ORDER['order_status']['locked']):

                if i.lock_time + timedelta(minutes=MOVIE_ORDER['lock_seat_expire_time']) >= now():
                    raise serializers.ValidationError('座位:{} 还在锁定中'.format(i))

            price = film_piece.online_price
            amount += price
        attrs['order_amount'] = amount
        return attrs

    class Meta:
        model = MovieOrders
        fields = ("user", 'order_seats', 'order_amount')
